<?php

use Phalcon\DI\FactoryDefault\CLI as CliDI,
    Phalcon\CLI\Console as ConsoleApp;
use Phalcon\Loader;
use Phalcon\Config\Adapter\Ini as ConfigIni;

define('VERSION', '1.0.0');


/**
 * 注册类自动加载器
 */
define('APP_PATH', realpath(__DIR__ . '/..') . '/');
$config = new ConfigIni(APP_PATH . 'app/configs/config.ini');
// Register an autoloader
$loader = new Loader();
$loader->registerDirs(array(
    APP_PATH . $config->application->tasksDir,
    APP_PATH . $config->application->modelsDir,
    APP_PATH . $config->application->libsDir,
    APP_PATH . $config->application->configsDir,
))->registerNamespaces(array(
    'App\Tasks' => APP_PATH . $config->application->tasksDir,
    'App\Models' => APP_PATH . $config->application->modelsDir,
    'App\Libs' => APP_PATH . $config->application->libsDir,
    'App\Configs' => APP_PATH . $config->application->configsDir,
));
$eventsManager = new \Phalcon\Events\Manager();

$eventsManager->attach('loader', function ($event, $loader) {
});

$loader->setEventsManager($eventsManager);

$loader->register();

// 使用CLI工厂类作为默认的服务容器
$di = new CliDI();
$di->set('session', function() {
    static $session = FALSE;
    if ($session !== FALSE) {
        return $session;
    }
    $session = \App\Libs\Session\ScriptSession::load();
    return $session;
});

// set config
\App\Libs\Base\Config::instance('script');

// 创建console应用
$console = new ConsoleApp();
$console->setDI($di);

/**
 * 处理console应用参数
 */
$arguments = array('task' => '\\App\\Tasks\\Main');
foreach ($argv as $k => $arg) {
    if ($k == 1) {
        $arguments['task'] = '\\App\\Tasks\\' . ucfirst($arg);
    } elseif ($k == 2) {
        $arguments['action'] = $arg;
    } elseif ($k >= 3) {
        $arguments['params'][] = $arg;
    }
}

// 定义全局的参数， 设定当前任务及动作
define('CURRENT_TASK',   (isset($argv[1]) ? $argv[1] : null));
define('CURRENT_ACTION', (isset($argv[2]) ? $argv[2] : null));

try {
    // 处理参数
    $console->handle($arguments);
} catch (\Phalcon\Exception $e) {
    echo $e->getMessage();
    exit(255);
}
